package org.csu.equipment.controller;

import com.alibaba.fastjson.JSON;
import org.csu.equipment.entity.*;
import org.csu.equipment.service.AdminService;
import org.csu.equipment.vo.Index2VO;
import org.csu.equipment.vo.UsingQuantity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static java.lang.Math.ceil;

@Controller
public class AdminController {

    @Autowired
    AdminService adminService;

    @GetMapping("/adminlogin")
    public String adminlogin(String CId, String CPwd, Model model) {
        System.out.println(CPwd);
        Integer c = adminService.login(CId, CPwd);
        if (c == 1) {
            List<Warehouse> warehouseList = adminService.getWareHouseList();// a c l p
            List<UsingQuantity> usingQuantityList = adminService.getUsingQuantity();//c p l a
            double fa = usingQuantityList.get(0).Add() / ((double) warehouseList.get(0).getQuantity() + usingQuantityList.get(0).Add());
            double fc = usingQuantityList.get(1).Add() / ((double) warehouseList.get(1).getQuantity() + usingQuantityList.get(1).Add());
            double fl = usingQuantityList.get(2).Add() / ((double) warehouseList.get(2).getQuantity() + usingQuantityList.get(2).Add());
            double fp = usingQuantityList.get(3).Add() / ((double) warehouseList.get(3).getQuantity() + usingQuantityList.get(3).Add());
            model.addAttribute("warehouseList", warehouseList);
            model.addAttribute("AId", CId);
            model.addAttribute("usingQuantityList", usingQuantityList);
            model.addAttribute("cQ", Integer.parseInt(new DecimalFormat("0").format(fc * 100)));
            model.addAttribute("pQ", Integer.parseInt(new DecimalFormat("0").format(fp * 100)));
            model.addAttribute("lQ", Integer.parseInt(new DecimalFormat("0").format(fl * 100)));
            model.addAttribute("aQ", Integer.parseInt(new DecimalFormat("0").format(fa * 100)));
            adminService.log(CId,"管理员登陆");
            return "admin/storage";
        }
        model.addAttribute("msg", "账户密码不正确");
        return "/index";
    }

    @GetMapping("/showWarehouse")
    public String showWarehouse(String AId, Model model) {
        List<Warehouse> warehouseList = adminService.getWareHouseList();// a c l p
        List<UsingQuantity> usingQuantityList = adminService.getUsingQuantity();//c p l a
        double fa = usingQuantityList.get(0).Add() / ((double) warehouseList.get(0).getQuantity() + usingQuantityList.get(0).Add());
        double fc = usingQuantityList.get(1).Add() / ((double) warehouseList.get(1).getQuantity() + usingQuantityList.get(1).Add());
        double fl = usingQuantityList.get(2).Add() / ((double) warehouseList.get(2).getQuantity() + usingQuantityList.get(2).Add());
        double fp = usingQuantityList.get(3).Add() / ((double) warehouseList.get(3).getQuantity() + usingQuantityList.get(3).Add());
        model.addAttribute("warehouseList", warehouseList);
        model.addAttribute("AId", AId);
        model.addAttribute("usingQuantityList", usingQuantityList);
        model.addAttribute("cQ", Integer.parseInt(new DecimalFormat("0").format(fc * 100)));
        model.addAttribute("pQ", Integer.parseInt(new DecimalFormat("0").format(fp * 100)));
        model.addAttribute("lQ", Integer.parseInt(new DecimalFormat("0").format(fl * 100)));
        model.addAttribute("aQ", Integer.parseInt(new DecimalFormat("0").format(fa * 100)));
        adminService.log(AId,"查看仓库信息");
        return "admin/storage";
    }


    @RequestMapping(value = "/submitIn", method = RequestMethod.GET)
    @ResponseBody
    public String submitIn(String AId, String AName, String AType, String AQuantity) {
        System.out.println(AType + AQuantity);
        adminService.in(AType, Integer.parseInt(AQuantity));
        String log = AName + " 购入" + AType + AQuantity + "件";
        adminService.log(AId, log);
        return "SUCCESS";
    }

    @GetMapping("/toCheckMaterial")
    public String toCheckMaterial(String AId, String pageNum, Model model) {
        List<Record> recordList = adminService.requestedtask();
        List<Record> viewMaterialList1;
        if (Integer.parseInt(pageNum) == ceil(recordList.size() / 4.0)) {
            viewMaterialList1 = recordList.subList(4 * Integer.parseInt(pageNum) - 4, recordList.size());
        } else {
            viewMaterialList1 = recordList.subList(4 * Integer.parseInt(pageNum) - 4, 4 * Integer.parseInt(pageNum));
        }
        model.addAttribute("viewMaterialList", viewMaterialList1);
        model.addAttribute("AId", AId);
        model.addAttribute("totalNum", ceil(recordList.size() / 4.0));
        model.addAttribute("pageNum", Integer.parseInt(pageNum));
        adminService.log(AId,"查看设备申请");
        return "admin/check";
    }

    @RequestMapping(value = "/submitAgree", method = RequestMethod.GET)
    @ResponseBody
    public String submitAgree(String RId) {
        if (!adminService.updateRecordAndTask(RId)) {
            return "unsuccessful";
        } else return "SUCCESS";
    }

    @GetMapping("/toCheckWorkers")
    public String toCheckWorkers(String AId, String pageNum, Model model) {
        List<Employee> employeeList = adminService.getEmployeeList();
        List<Employee> employeeList1;
        if (Integer.parseInt(pageNum) == ceil(employeeList.size() / 3.0)) {
            employeeList1 = employeeList.subList(3 * Integer.parseInt(pageNum) - 3, employeeList.size());
        } else {
            employeeList1 = employeeList.subList(3 * Integer.parseInt(pageNum) - 3, 3 * Integer.parseInt(pageNum));
        }
        model.addAttribute("employeeList", employeeList1);
        model.addAttribute("AId", AId);
        model.addAttribute("totalNum", ceil(employeeList.size() / 3.0));
        model.addAttribute("pageNum", Integer.parseInt(pageNum));
        adminService.log(AId,"查看工人信息");
        return "admin/info-employee";
    }

    @GetMapping("/toCheckClients")
    public String toCheckClients(String AId, String pageNum, Model model) {
        List<Client> clientList = adminService.getClientList();
        List<Client> clientList1;
        if (Integer.parseInt(pageNum) == ceil(clientList.size() / 3.0)) {
            clientList1 = clientList.subList(3 * Integer.parseInt(pageNum) - 3, clientList.size());
        } else {
            clientList1 = clientList.subList(3 * Integer.parseInt(pageNum) - 3, 3 * Integer.parseInt(pageNum));
        }
        model.addAttribute("clientList", clientList1);
        model.addAttribute("AId", AId);
        model.addAttribute("totalNum", ceil(clientList.size() / 3.0));
        model.addAttribute("pageNum", Integer.parseInt(pageNum));
        adminService.log(AId,"查看职员信息");
        return "admin/info-workers";
    }

    @RequestMapping(value = "/newClient", method = RequestMethod.POST)
    @ResponseBody
    public String newClient(Client client,String CPwd) {
        for (Field f : client.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            try {
                if (f.get(client) == null || "".equals(f.get(client).toString())) { //判断字段是否为空，并且对象属性中的基本都会转为对象类型来判断
                    return "null";
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(CPwd.equals("")){
            return "null";
        }
        ClientLogin clientLogin = new ClientLogin();
        clientLogin.setCId(client.getCId());
        clientLogin.setCPwd(CPwd);
        adminService.insertCinfo(client,clientLogin);
        return "success";
    }

    @RequestMapping( value = "/newEmployee" ,method = RequestMethod.POST)
    @ResponseBody
    public String newEmployee(Employee employee,String EPwd,EmployeeSkill employeeSkill){
        employee.setEStatus(true);
        for(Field f :employee.getClass().getDeclaredFields()){
            f.setAccessible(true);
            try {
                if(f.get(employee) == null || "".equals(f.get(employee).toString()))
                    return "null";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(EPwd.equals("")){
            return "null";
        }
        if(employeeSkill.getElevator()==null) employeeSkill.setElevator(false);
        if(employeeSkill.getPrinter()==null) employeeSkill.setPrinter(false);
        if(employeeSkill.getComputer()==null) employeeSkill.setComputer(false);
        if(employeeSkill.getLight()==null) employeeSkill.setLight(false);
        if(employeeSkill.getAirController()==null) employeeSkill.setAirController(false);

        EmployeeLogin employeeLogin = new EmployeeLogin();
        employeeLogin.setEId(employee.getEId());
        employeeLogin.setEPwd(EPwd);
        adminService.insertEinfo(employee,employeeLogin,employeeSkill);
        return "success";
    }

    @GetMapping("/toCheckTasks")
    public String toCheckTasks(String AId, String pageNum, Model model) {
        List<Task> taskList = adminService.getTaskList();
        List<Task> taskList1;
        if (Integer.parseInt(pageNum) == ceil(taskList.size() / 5.0)) {
            taskList1 = taskList.subList(5 * Integer.parseInt(pageNum) - 5, taskList.size());
        } else {
            taskList1 = taskList.subList(5 * Integer.parseInt(pageNum) - 5, 5 * Integer.parseInt(pageNum));
        }
        model.addAttribute("taskList", taskList1);
        model.addAttribute("AId", AId);
        model.addAttribute("totalNum", ceil(taskList.size() / 5.0));
        model.addAttribute("pageNum", Integer.parseInt(pageNum));
        adminService.log(AId,"查看报修订单信息");
        return "admin/info-charts";
    }

    @RequestMapping(value = "/submitDisagree", method = RequestMethod.GET)
    @ResponseBody
    public String submitDisagree(String TId) {
        adminService.cancelTask(TId);
        return "SUCCESS";
    }

    @GetMapping("/showStatistics")
    public String showStatistics(String AId,Model model){
        List<Employee> employeeList = adminService.employeeRank();
        Index2VO index2VO = adminService.getIndex2VO();
        index2VO.setGNumber(adminService.Tasknumber(employeeList.get(0).getEId()));
        index2VO.setSNumber(adminService.Tasknumber(employeeList.get(1).getEId()));
        index2VO.setMNumber(adminService.Tasknumber(employeeList.get(2).getEId()));
        adminService.log(AId,"查看维修统计信息");
        model.addAttribute("index2VO",index2VO);
        model.addAttribute("employeeList",employeeList);
        model.addAttribute("AId",AId);
        return "admin/index-2";
    }

    @GetMapping("/lock")
    public  String lock(String AId,Model model){
        AdminLogin adminLogin = new AdminLogin();
        adminLogin.setAId(AId);
        model.addAttribute("admin",adminLogin);
        return "admin/lock";
    }

    @GetMapping("/unlock")
    public String unlock(String AId ,String APwd ,Model model){
        Integer c = adminService.login(AId,APwd);
        if(c == 1){
            List<Employee> employeeList = adminService.employeeRank();
            Index2VO index2VO = adminService.getIndex2VO();
            index2VO.setGNumber(adminService.Tasknumber(employeeList.get(0).getEId()));
            index2VO.setSNumber(adminService.Tasknumber(employeeList.get(1).getEId()));
            index2VO.setMNumber(adminService.Tasknumber(employeeList.get(2).getEId()));
            adminService.log(AId,"解锁屏保");
            model.addAttribute("index2VO",index2VO);
            model.addAttribute("employeeList",employeeList);
            model.addAttribute("AId",AId);
            return "admin/index-2";
        }
        else{
            model.addAttribute("msg","密码错误");
            AdminLogin adminLogin = new AdminLogin();
            adminLogin.setAId(AId);
            model.addAttribute("admin",adminLogin);
            return "admin/lock";
        }

    }

    @GetMapping("/signOut")
    public String signOut(){
        return "index";
    }

    @GetMapping("/priority")
    public String priority(String AId ,Model model){
        model.addAttribute("AId",AId);
        return "admin/priority";
    }

    @GetMapping("/log")
    public String log(String AId,String pageNum,String startTime,String endTime,Model model){
        model.addAttribute("startTime",startTime);
        model.addAttribute("endTime",endTime);
        Timestamp st = Timestamp.valueOf(startTime.replaceAll("T", " ") + ":00");
        Timestamp et = Timestamp.valueOf(endTime.replaceAll("T", " ") + ":00");
        List<AdminLog> adminLogList = adminService.getLogInTime(AId,st,et);
        List<AdminLog> adminLogs;
        if (Integer.parseInt(pageNum) == ceil(adminLogList.size() / 6.0)) {
            adminLogs = adminLogList.subList(6 * Integer.parseInt(pageNum) - 6, adminLogList.size());
        } else {
            adminLogs = adminLogList.subList(6 * Integer.parseInt(pageNum) - 6, 6 * Integer.parseInt(pageNum));
        }
        model.addAttribute("adminLogList", adminLogs);
        model.addAttribute("AId", AId);
        model.addAttribute("totalNum", ceil(adminLogList.size() / 6.0));
        model.addAttribute("pageNum", Integer.parseInt(pageNum));
        adminService.log(AId,"查看日志");
        return "admin/log";
    }

    @RequestMapping(value = "/getAClient", method = RequestMethod.GET)
    @ResponseBody
    public String getAClient(String CId) {
        Client client = adminService.getAClient(CId);
        if(client==null){
            return "NotFound";
        }
        return JSON.toJSONString(client);
    }

    @RequestMapping(value = "/getAEmployee", method = RequestMethod.GET)
    @ResponseBody
    public String getAEmployee(String EId) {
       Employee employee = adminService.getAEmployee(EId);
        if(employee==null){
            return "NotFound";
        }
        return JSON.toJSONString(employee);
    }

}
